﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Template;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Having.Site.Route
{
    /// <summary>
    /// 路由中间件
    /// </summary>
    public class RouteMiddleware : IMiddleware
    {
        /// <summary>
        /// 中间件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var spath = context.Request.PathBase + context.Request.Path;
            foreach (var spitem in RouteCollection.ItemCollection)
            {
                //正则验证
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex(spitem.regstring);
                if (Regex.IsMatch(spath))
                {
                    var routeData = new RouteValueDictionary();
                    var Tm = new TemplateMatcher(spitem.rt, null);
                    if (Tm.TryMatch(spath, routeData))
                    {
                        RouteContext routeContext = new RouteContext(context);
                        routeContext.RouteData = new RouteData(routeData);
                        context.Features.Set<IRoutingFeature>(new RoutingFeature { RouteData = routeContext.RouteData });
                        await spitem.action(context);
                        break;
                    }
                }
            }
            try
             {
                if (next != null)
                {
                    await next(context);
                }
            }
            catch { }
        }
    }
}
